// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package address

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"server/app/lib/maps"
)

// Logic
// 保存钓场名称.
type Logic struct {
	admin   *models.ArcadeAdmins
	arcade  *models.Arcades
	affects int64

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置结果.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade,
			o.admin,
			kind.ArcadeAdminOperationUpdateArcadeAddress,
			kind.ArcadeAdminOperationUpdateArcadeAddress.ToUpdateArcadeAddress(o.arcade.Address, o.request.Address),
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	if err = o.RunAddress(ctx); err == nil {
		err = o.RunUpdate(ctx)
	}
	if err != nil {
		return res.WithError(err)
	}

	o.response.Address = o.request.Address
	o.response.Latitude = o.request.Latitude
	o.response.Longitude = o.request.Longitude
	return res.With(o.response)
}

func (o *Logic) RunAddress(ctx context.Context) (err error) {
	var loc maps.Location

	// 1. 地图取点.
	if loc, err = lib.Maps.GetAddressByLocation(ctx, o.request.Latitude, o.request.Longitude); err != nil {
		return
	}

	// 2. 保存取点.
	_, err = services.NewArcadeLocationService().Dao.UpdateFieldsByMap(ctx, map[string]any{
		"code":      loc.Code,
		"city_code": loc.CityCode,
		"province":  loc.Province,
		"city":      loc.City,
		"district":  loc.District,
		"street":    loc.Street,
	}, map[string]any{
		"arcade_id": o.arcade.Id,
	})
	return err
}

func (o *Logic) RunUpdate(ctx context.Context) (err error) {
	if o.affects, err = services.NewArcadesService().Dao.UpdateFieldsById(ctx, map[string]any{
		"address":   o.request.Address,
		"latitude":  o.request.Latitude,
		"longitude": o.request.Longitude,
	}, o.arcade.Id); err != nil {
		log.Infofc(ctx, `arcade address updated: affects="%d"`, o.affects)
	}
	return
}
